package com.nexus.plugin.amqp.handle;

import com.nexus.core.exception.AmqpQueueException;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.RabbitListenerErrorHandler;
import org.springframework.amqp.rabbit.support.ListenerExecutionFailedException;
import org.springframework.stereotype.Component;


/**
 * 自定义RabbitMQ错误处理器
 * 统一处理消息消费过程中的异常
 *
 * @Date 2025/9/24 15:21
 * @Author luzhengning
 **/
@Slf4j
@Component("nexusRabbitErrorHandler")
public class NexusRabbitErrorHandler implements RabbitListenerErrorHandler {

    @Override
    public Object handleError(Message ampqMessage, Channel channel, org.springframework.messaging.Message<?> message1, ListenerExecutionFailedException e) throws Exception {
        String queue = ampqMessage.getMessageProperties().getConsumerQueue();
        String messageId = ampqMessage.getMessageProperties().getMessageId();

        log.error("消息消费失败 - 队列: {}, 消息ID: {}, 异常: {}",
                queue, messageId, e.getMessage(), e);

        // 根据异常类型进行不同处理
        if (e.getCause() instanceof AmqpQueueException) {
            // 业务异常，可能不需要重试
            log.warn("业务异常，消息进入死信队列 - 消息ID: {}", messageId);
            throw e; // 抛出异常让消息进入死信队列
        } else {
            // 系统异常，可以重试
            log.warn("系统异常，消息将重试 - 消息ID: {}", messageId);
            throw e; // 抛出异常触发重试机制
        }
    }
}